package com.chagee.store.operation.server.service.biz;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chagee.base.utils.PaginationData;
import com.chagee.base.utils.PaginationRequest;
import com.chagee.store.operation.api.enums.*;
import com.chagee.store.operation.api.request.AcceptanceOrderRequest;
import com.chagee.store.operation.api.request.AcceptanceRequest;
import com.chagee.store.operation.api.request.TaskAcceptanceRequest;
import com.chagee.store.operation.api.response.vo.AiResultVO;
import com.chagee.store.operation.common.exception.BizErrorCode;
import com.chagee.store.operation.common.exception.BizException;
import com.chagee.store.operation.common.utils.ResponseUtil;
import com.chagee.store.operation.server.aop.IgnoreTenant;
import com.chagee.store.operation.server.entity.*;
import com.chagee.store.operation.server.event.dao.TaskExecutionMapper;
import com.chagee.store.operation.server.event.mq.producer.MqMessageService;
import com.chagee.store.operation.server.event.service.BasicTaskConfigurationService;
import com.chagee.store.operation.server.event.service.StoreOrderDeviceBaseService;
import com.chagee.store.operation.server.event.service.StoreTaskRelationBaseService;
import com.chagee.store.operation.server.event.service.TaskExecutionBaseService;
import com.chagee.store.operation.server.event.service.WorkOrderBaseService;
import com.chagee.store.operation.server.event.service.WorkOrderReceiverBaseService;
import com.chagee.store.operation.server.hadler.StoreIssueNotice;
import com.chagee.store.operation.server.model.param.*;
import com.chagee.store.operation.server.model.vo.*;
import com.personnel.auth.service.PersonnelAuthService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.ObjectUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author : hk
 * @Date : 2024/7/31
 */

@Service
@Slf4j
@RequiredArgsConstructor
public class StoreAppSweepBizService {

	@Resource
	private TaskExecutionBaseService taskExecutionBaseService;
	@Resource
	private StoreTaskRelationBaseService storeTaskRelationBaseService;
	@Resource
	private BasicTaskConfigurationService basicTaskConfigurationService;
	@Resource
	private WorkOrderReceiverBaseService workOrderReceiverBaseService;
	@Resource
	private PersonnelAuthService personnelAuthService;
	@Resource
	private StoreOrderDeviceBaseService storeOrderDeviceBaseService;
	@Resource
	private WorkOrderBaseService workOrderBaseService;

	@Resource
	private TaskExecutionMapper taskExecutionMapper;
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;

	@Resource
	private MqMessageService mqMessageService;

	/**
	 * 工单AI分析异常通知发消息给iot
	 *
	 * @param param
	 * @return
	 */
	public boolean sendMessage(StoreIssueNotice param) {
		boolean result = mqMessageService.sendMessage(param);
		return result;
	}

	@IgnoreTenant(isIgnore = false)
	public PaginationData<QueryStoreTaskResponse> queryList(PaginationRequest<StoreAppSweepQueryParam> request) {
		Page<TaskExecutionDO> page = new Page<>(request.getPageNum(), request.getPageSize());
		Page<TaskExecutionDO> list = taskExecutionBaseService.waitTaskList(request.getQueryParameter(), page);
		if (StringUtils.equals("1",request.getQueryParameter().getType())) {
			list = taskExecutionBaseService.queryList(request.getQueryParameter(), page);
		}
		if (CollectionUtils.isEmpty(list.getRecords())) {
			return ResponseUtil.emptyResponse(request, QueryStoreTaskResponse.class, list.getTotal());
		}
		List<QueryStoreTaskResponse> taskResponses = converToTasktVO(list.getRecords());

		return ResponseUtil.commonResponse(request, taskResponses, list.getTotal());
	}

	private List<QueryStoreTaskResponse> converToTasktVO(List<TaskExecutionDO> dos) {
		List<QueryStoreTaskResponse> list = dos.stream().map(s -> {
			QueryStoreTaskResponse tasktVO = new QueryStoreTaskResponse();
			BeanUtil.copyProperties(s, tasktVO);
			if (StringUtils.equals(s.getEarlyAcceptance(),StoreTaskEnum.NO.getType())) {
				tasktVO.setSortNum(NumberUtils.INTEGER_ONE);
			} else {
				tasktVO.setSortNum(NumberUtils.INTEGER_ZERO);
			}
			tasktVO.setEarlyAcceptance(StringUtils.isNotEmpty(s.getEarlyAcceptance()) ? com.chagee.storeManagement.api.event.enums.StoreTaskEnum.queryByType(s.getEarlyAcceptance()).getDesc() : "");
			tasktVO.setSchematicDrawing(StringUtils.isNotEmpty(s.getSchematicDrawing()) ? JSONArray.parseArray(s.getSchematicDrawing(), FileVO.class) : new ArrayList<>());
			tasktVO.setTakePictures(StringUtils.isNotEmpty(s.getTakePictures()) ? JSONArray.parseArray(s.getTakePictures(), AiResultVO.class) : new ArrayList<>());
			tasktVO.setRemarkPicture(StringUtils.isNotEmpty(s.getRemarkPicture()) ? JSONArray.parseArray(s.getRemarkPicture(), FileVO.class) : new ArrayList<>());
			return tasktVO;
		}).sorted(Comparator.comparing(QueryStoreTaskResponse::getSortNum, Comparator.reverseOrder())).collect(Collectors.toList());
		return list;
	}

	public PaginationData<QueryStoreTaskResponse> queryOrderTaskList(PaginationRequest<OrderTaskListParam> request) {
		Page<TaskExecutionDO> page = new Page<>(request.getPageNum(), request.getPageSize());
		Page<TaskExecutionDO> list = taskExecutionMapper.waitTask(page, request.getQueryParameter());
		if (StringUtils.equals("1",request.getQueryParameter().getType())) {
			list = taskExecutionMapper.selectAlready(page, request.getQueryParameter());
		}
		if (CollectionUtils.isEmpty(list.getRecords())) {
			return ResponseUtil.emptyResponse(request, QueryStoreTaskResponse.class, list.getTotal());
		}
		List<QueryStoreTaskResponse> taskResponses = converToTasktVO(list.getRecords());

		return ResponseUtil.commonResponse(request, taskResponses, list.getTotal());
	}

	/**
	 * 门店本月单据状态详情
	 *
	 * @param param
	 * @return
	 */
	@IgnoreTenant(isIgnore = false)
	public StoreMonthOrderVO storeMonthOrder(MonthOrderParam param) {

		Map<Object, String> hashMap = new HashMap<>();
		hashMap.put("storeCode", param.getStoreNo());
		hashMap.put("startDate", param.getStartDate());
		hashMap.put("endDate", param.getEndDate());

		List<WorkOrderDO> taskExecutionDOList = workOrderBaseService.selectMonthOrder(hashMap);
		List<StoreOderVO> voList = taskExecutionDOList.stream().map(s -> {
			StoreOderVO vo = new StoreOderVO();
			BeanUtils.copyProperties(s, vo);
			vo.setCreateTime(DateUtil.format(s.getCreateTime(), "yyyy-MM-dd"));
			return vo;
		}).collect(Collectors.toList());

		Map<String, List<StoreOderVO>> map = voList.stream().collect(Collectors.groupingBy(StoreOderVO::getCreateTime));
		StoreMonthOrderVO response = new StoreMonthOrderVO();
		response.setStoreOderList(map);

		return response;
	}

	/**
	 * 门店最近打烊工单日期
	 *
	 * @param param
	 * @return
	 */
	public String queryOrderDate(StoreWordInfoParam param) {
		Map<Object, String> hashMap = new HashMap<>();
		hashMap.put("storeCode", param.getStoreNo());
		List<WorkOrderDO> taskExecutionDOList = workOrderBaseService.queryOrderDate(hashMap);
		if (CollectionUtils.isNotEmpty(taskExecutionDOList)) {
			Optional<WorkOrderDO> optional = taskExecutionDOList.stream().sorted(Comparator.comparing(WorkOrderDO::getId,
				Comparator.reverseOrder())).findFirst();
			if (optional.isPresent()) {
				String orderDate = DateUtil.format(optional.get().getCreateTime(), DatePattern.NORM_DATE_PATTERN);
				return orderDate;
			}
		}
		return null;
	}

	/**
	 * 打烊任务工单
	 * @param request
	 * @return
	 */
	public List<StoreOderInfoVO> storeOrder(PaginationRequest<StoreAppSweepQueryParam> request){
		List<WorkOrderDO> orderDOS = workOrderBaseService.selectOrderList(request.getQueryParameter());
		if (CollectionUtils.isEmpty(orderDOS)){
			return new ArrayList<>();
		}
		QueryWrapper<TaskExecutionDO> query = Wrappers.query();
		query.eq("work_order_number",orderDOS.get(0).getWorkOrderNumber());
		List<TaskExecutionDO> list = taskExecutionBaseService.list(query);

		List<StoreOderInfoVO> infoList = orderDOS.stream().map(s ->{
			StoreOderInfoVO info =new StoreOderInfoVO();
			info.setId(s.getId());
			info.setWorkOrderNumber(s.getWorkOrderNumber());
			info.setStoreCode(s.getStoreCode());
			info.setStoreName(s.getStoreName());
			info.setDocumentType(OrderStatusEnum.getByType(s.getDocumentType()).getDesc());
			info.setDocumentStatus(StoreWorkOrderStatusEnum.getByType(s.getDocumentStatus()).getDesc());
			info.setDocumentScore(s.getDocumentScore());
			if (StringUtils.isNotBlank(s.getReceiver()) && StringUtils.isNotBlank(s.getReceiverMobile())){
				String[] receiver =s.getReceiver().split(",");
				String[] receiverMobile =s.getReceiverMobile().split(",");

				List<String> encryptPhoneList =new ArrayList<>();
				for (String phone : receiverMobile){
					String phoneNumber =phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
					encryptPhoneList.add(phoneNumber);
				}
				receiverMobile =encryptPhoneList.toArray(new String[0]);
				String result =joinStringArrays(receiver,receiverMobile);
				info.setReceiver(result);
			}
//			info.setReceiver(s.getReceiver());
			info.setSupplier(s.getSupplier());
			info.setExtra(s.getExtra());
			info.setCreateTime(DateUtil.format(s.getCreateTime(),DatePattern.NORM_DATETIME_PATTERN));
			info.setTransfer(s.getTransfer());
			info.setDeviceTakeOver(s.getDeviceTakeOver());
			info.setOrderTaskNum(list.size());
			return info;
		}).collect(Collectors.toList());
		return infoList;
	}

	public StoreOderInfoVO queryOrderDetail(QueryOrderDetailParam queryParam) {
		LambdaQueryWrapper<WorkOrderDO> queryOrderWrapper = new LambdaQueryWrapper<>();
		queryOrderWrapper.eq(WorkOrderDO::getWorkOrderNumber, queryParam.getWorkOrderNumber())
			.eq(WorkOrderDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);

		List<WorkOrderDO> list = workOrderBaseService.list(queryOrderWrapper);
		WorkOrderDO workOrderDO = list.stream().findFirst().orElseThrow(() -> new BizException(BizErrorCode.ORDER_NOT_EXIST));

		LambdaQueryWrapper<TaskExecutionDO> query = new LambdaQueryWrapper<>();
		query.eq(TaskExecutionDO::getWorkOrderNumber, queryParam.getWorkOrderNumber());
		List<TaskExecutionDO> taskExecutionDOS = taskExecutionBaseService.list(query);

		StoreOderInfoVO info = new StoreOderInfoVO();
		info.setId(workOrderDO.getId());
		info.setWorkOrderNumber(workOrderDO.getWorkOrderNumber());
		info.setStoreCode(workOrderDO.getStoreCode());
		info.setStoreName(workOrderDO.getStoreName());
		info.setDocumentType(OrderStatusEnum.getByType(workOrderDO.getDocumentType()).getDesc());
		info.setDocumentStatus(StoreWorkOrderStatusEnum.getByType(workOrderDO.getDocumentStatus()).getDesc());
		info.setDocumentScore(workOrderDO.getDocumentScore());
		if (StringUtils.isNotBlank(workOrderDO.getReceiver()) && StringUtils.isNotBlank(workOrderDO.getReceiverMobile())) {
			String[] receiver = workOrderDO.getReceiver().split(",");
			String[] receiverMobile = workOrderDO.getReceiverMobile().split(",");

			List<String> encryptPhoneList = new ArrayList<>();
			for (String phone : receiverMobile) {
				String phoneNumber = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
				encryptPhoneList.add(phoneNumber);
			}
			receiverMobile = encryptPhoneList.toArray(new String[0]);
			String result = joinStringArrays(receiver, receiverMobile);
			info.setReceiver(result);
		}
		info.setSupplier(workOrderDO.getSupplier());
		info.setExtra(workOrderDO.getExtra());
		info.setCreateTime(DateUtil.format(workOrderDO.getCreateTime(), DatePattern.NORM_DATETIME_PATTERN));
		info.setTransfer(workOrderDO.getTransfer());
		info.setDeviceTakeOver(workOrderDO.getDeviceTakeOver());
		info.setOrderTaskNum(taskExecutionDOS.size());
		return info;
	}

	public QueryStoreTaskResponse taskDetail(StoreTaskInfoRequest request) {
		QueryWrapper<TaskExecutionDO> query = Wrappers.query();
		query.eq("id", request.getId());
		List<TaskExecutionDO> list = taskExecutionBaseService.list(query);
		TaskExecutionDO taskExecutionDO = list.stream().findFirst().orElseThrow(() -> new BizException(BizErrorCode.ORDER_NOT_EXIST));

		QueryStoreTaskResponse response = new QueryStoreTaskResponse();
		BeanUtil.copyProperties(taskExecutionDO, response);
		response.setEarlyAcceptance(StringUtils.isNotEmpty(taskExecutionDO.getEarlyAcceptance()) ? com.chagee.storeManagement.api.event.enums.StoreTaskEnum.queryByType(taskExecutionDO.getEarlyAcceptance()).getDesc() : "");
		response.setSchematicDrawing(StringUtils.isNotEmpty(taskExecutionDO.getSchematicDrawing()) ? JSONArray.parseArray(taskExecutionDO.getSchematicDrawing(), FileVO.class) : new ArrayList<>());
		response.setTakePictures(StringUtils.isNotEmpty(taskExecutionDO.getTakePictures()) ? JSONArray.parseArray(taskExecutionDO.getTakePictures(), AiResultVO.class) : new ArrayList<>());
		response.setRemarkPicture(StringUtils.isNotEmpty(taskExecutionDO.getRemarkPicture()) ? JSONArray.parseArray(taskExecutionDO.getRemarkPicture(), FileVO.class) : new ArrayList<>());
		return response;
	}


	@Transactional(rollbackFor = Exception.class)
	public ScanResponse taskAcceptance(AcceptanceRequest request) {
		LambdaQueryWrapper<WorkOrderDO> queryOrderWrapper = new LambdaQueryWrapper<>();
		queryOrderWrapper.eq(WorkOrderDO::getWorkOrderNumber, request.getTaskAcceptanceParam().get(0).getWorkOrderNumber());
		WorkOrderDO orderDOList = workOrderBaseService.getOne(queryOrderWrapper);
		WorkOrderDO workOrderDO = Optional.ofNullable(orderDOList).orElseThrow(() -> new BizException(BizErrorCode.NO_WORK_ORDER_DATA));
		if (!StoreWorkOrderStatusEnum.TO_BE_ACCEPTED.getType().equals(workOrderDO.getDocumentStatus())){
			throw new BizException(BizErrorCode.ORDER_STATUS_FAIL);
		}
		QueryWrapper<TaskExecutionDO> query = Wrappers.query();
		query.eq("work_order_number", request.getTaskAcceptanceParam().get(0).getWorkOrderNumber());
		List<TaskExecutionDO> allTaskList = taskExecutionBaseService.list(query);

		/*PersonnelInfo user = null;
		try {
			user = personnelAuthService.getLoginUserInfoInServer();
		} catch (Exception e) {
			log.error("personnelAuthService.getLoginUserInfoInServer throw exception. {}", e.getMessage());
		}*/
		if (CollectionUtils.isNotEmpty(allTaskList)) {
			/*boolean b = allTaskList.stream().allMatch(s -> StringUtils.isNotBlank(s.getEarlyAcceptance()));
			if (b) {
				throw new BizException(BizErrorCode.ORDER_NOT_EXIST, "本工单已验收完成，提交失败");
			}*/
			//全选操作
			if (StringUtils.equals("1", request.getIsAll()) && StringUtils.isNotBlank(request.getAllEarlyAcceptance())) {
				allTaskList = allTaskList.stream().filter(s -> StringUtils.isBlank(s.getEarlyAcceptance())).peek(s -> {
					s.setEarlyAcceptance(request.getAllEarlyAcceptance());
					s.setAppraiser(request.getLoginInfo());
					s.setReliableTime(new Date());
				}).collect(Collectors.toList());
			} else {
				Map<String, TaskAcceptanceRequest> map = request.getTaskAcceptanceParam().stream().collect(Collectors.toMap(TaskAcceptanceRequest::getId, Function.identity(), (s1, s2) -> s1));
				for (TaskExecutionDO taskExecutionDO : allTaskList) {
					TaskAcceptanceRequest acceptanceRequest = map.get(taskExecutionDO.getId().toString());
					if (ObjectUtil.isNotEmpty(acceptanceRequest)) {
						taskExecutionDO.setEarlyAcceptance(acceptanceRequest.getEarlyAcceptance());
						if (StringUtils.equals(StoreTaskEnum.NO.getType(), acceptanceRequest.getEarlyAcceptance())) {
							//不满意仅支持单选数据
							taskExecutionDO.setRemark(StringUtils.isNotEmpty(acceptanceRequest.getRemark()) ? acceptanceRequest.getRemark() : null);
							taskExecutionDO.setRemarkPicture(CollectionUtils.isNotEmpty(acceptanceRequest.getRemarkPicture()) ? JSON.toJSONString(acceptanceRequest.getRemarkPicture()) : null);
						}
						//String userNo = StringUtils.isNotBlank(user.getFeishuEmpNo()) ? user.getFeishuEmpNo() : "";
						//taskExecutionDO.setAppraiser(StringUtils.isNotBlank(user.getName()) ? user.getName() : "" + "(" + userNo + ")");
						taskExecutionDO.setAppraiser(request.getLoginInfo());
						taskExecutionDO.setReliableTime(new Date());
					}
				}
			}
			taskExecutionBaseService.updateBatchById(allTaskList);
			return new ScanResponse(BizErrorCode.HTTP_SUCCESS.getErrorCode(), BizErrorCode.HTTP_SUCCESS.getErrorMsg(), null);
		}
		return new ScanResponse(BizErrorCode.HTTP_SUCCESS.getErrorCode(), "该工单无任务", null);
	}

	public Boolean orderAcceptance(AcceptanceOrderRequest request) {
		Map<Object, String> map = new HashMap<>();
		map.put("workOrderNumber", request.getWorkOrderNumber());
		WorkOrderDO workOrderDO = workOrderBaseService.orderAcceptance(map).stream().findFirst().orElse(null);
		if (ObjectUtil.isEmpty(workOrderDO)) {
			throw new BizException(BizErrorCode.ORDER_NOT_EXIST);
		}
		if (StoreWorkOrderStatusEnum.COMPLETED.getType().equals(workOrderDO.getDocumentStatus())) {
			throw new BizException(BizErrorCode.ORDER_ACCEPTANCE_FAIL);
		}
//		QueryWrapper<TaskExecutionDO> query = Wrappers.query();
//		query.eq("work_order_number", request.getWorkOrderNumber());
//		List<TaskExecutionDO> taskExecutionDOS = taskExecutionBaseService.list(query);

		List<String> workOrders = new ArrayList<>();
		//前两天工单
		List<WorkOrderDO> workOrderDOList = workOrderBaseService.queryOrder(workOrderDO.getId(),workOrderDO.getStoreCode());
		log.info("orderAcceptance_queryOrder: {}", JSON.toJSON(workOrderDOList));
		if (CollectionUtil.isNotEmpty(workOrderDOList)) {
			workOrders = workOrderDOList.stream().map(WorkOrderDO::getWorkOrderNumber).collect(Collectors.toList());
		}
		workOrders.add(request.getWorkOrderNumber());

		List<TaskExecutionDO> taskExecutionDOList = taskExecutionBaseService.queryTaskList(workOrders);
		log.info("orderAcceptance_task: {}", JSON.toJSON(taskExecutionDOList));

		Set<String> taskIds = taskExecutionDOList.stream().map(TaskExecutionDO::getTaskId).collect(Collectors.toSet());

		Map<String, List<TaskExecutionDO>> listMap = taskExecutionDOList.stream().collect(Collectors.groupingBy(TaskExecutionDO::getWorkOrderNumber));
		List<TaskExecutionDO> taskExecutionDOS = listMap.get(request.getWorkOrderNumber());
		if (CollectionUtils.isNotEmpty(taskExecutionDOS)) {
			boolean b = taskExecutionDOS.stream().anyMatch(s -> StringUtils.isBlank(s.getEarlyAcceptance()));
			if (b) {
				throw new BizException(BizErrorCode.NOT_ACCEPTANCE_FAIL);
			}
			boolean standard = false;
			for (String taskId : taskIds) {
				int taskFlag = 0;
				for (Map.Entry<String, List<TaskExecutionDO>> entry : listMap.entrySet()) {
					List<TaskExecutionDO> dos = entry.getValue().stream().filter(t -> StringUtils.equals(taskId, t.getTaskId()) && StoreTaskEnum.NO.getType().equals(t.getEarlyAcceptance())).collect(Collectors.toList());
					if (CollectionUtil.isNotEmpty(dos)) {
						taskFlag++;
					}
				}
				// 其中一个任务连续三日不合格,则符合强制工单不合格
				if (taskFlag >= 3) {
					log.info("WorkOrderNumber: {} , taskId:{}", request.getWorkOrderNumber(), taskId);
					standard = true;
					break;
				}
			}

			//工单状态为待验收且任务皆已验收
			if (!b && StoreWorkOrderStatusEnum.TO_BE_ACCEPTED.getType().equals(workOrderDO.getDocumentStatus())) {
				workOrderDO.setDocumentStatus(StoreWorkOrderStatusEnum.COMPLETED.getType());//已完成
				workOrderDO.setAcceptanceCompletionTime(new Date());
				workOrderDO.setAcceptanceType(OrderAcceptanceTypeEnum.HAND.name());
				List<TaskExecutionDO> yesOrders = taskExecutionDOS.stream().filter(s -> StringUtils.equals("1", s.getEarlyAcceptance())).collect(Collectors.toList());
				List<TaskExecutionDO> emptyOrders = taskExecutionDOS.stream().filter(s -> StringUtils.equals("3", s.getEarlyAcceptance())).collect(Collectors.toList());
				if (standard) {
					//强制不合格标识
					workOrderDO.setContinuousAcceptance(OrderTaskAcceptanceEnum.NO_PASS.getType());
					workOrderDO.setDocumentScore("0");
				} else if (!CollectionUtils.isEmpty(yesOrders)) {
					// 工单评分  满意数量 / (总数量- 验收无此项) * 100
					BigDecimal score = new BigDecimal(yesOrders.size() * 100).divide(new BigDecimal(taskExecutionDOS.size() - emptyOrders.size()), 0, BigDecimal.ROUND_HALF_UP);
					workOrderDO.setDocumentScore(score.toString());
				} else {
					workOrderDO.setDocumentScore("0");
				}

				LambdaQueryWrapper<WorkOrderReceiverDO> queryWrapper = new LambdaQueryWrapper<>();
				queryWrapper.eq(WorkOrderReceiverDO::getWorkOrderNumber, request.getWorkOrderNumber());
				List<WorkOrderReceiverDO> workOrderReceiverDOS = workOrderReceiverBaseService.list(queryWrapper);
				workOrderReceiverDOS.forEach(s -> {
					s.setDocumentStatus(StoreWorkOrderStatusEnum.COMPLETED.getType());
					s.setDocumentScore(workOrderDO.getDocumentScore());
				});
				workOrderReceiverBaseService.updateBatchById(workOrderReceiverDOS);
				return workOrderBaseService.updateById(workOrderDO);
			}
		}
		return false;
	}

	private static String joinStringArrays(String[] name,String[] phone){
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < name.length; i++) {
			sb.append(name[i]).append("(")
				.append(phone[i % phone.length])
				.append("),");
		}
		return sb.deleteCharAt(sb.lastIndexOf(",")).toString();
	}

}
